package reviewAlgorithms.search;

import java.util.ArrayList;
import java.util.List;

public class CombinationSum3 {
    public static void main(String[] args) {
        int k = 3;
        int n = 15;
        List<List<Integer>> res = combinationSum3(k,n);
        for (List<Integer> item : res){
            System.out.println(item);
        }
    }

    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        if (n < 1 || k > n || k > 9){
            return res;
        }
        List<Integer> oneRes = new ArrayList<>();
        int level = 1;
        int start = 1;
        getCombinationSum3(k,n,level,start,res,oneRes);
        return res;
    }

    private static void getCombinationSum3(int k, int n, int level, int start, List<List<Integer>> res, List<Integer> oneRes) {
        if (level > k){
            int sum = 0;
            for (Integer num: oneRes) {
                sum += num;
            }
            if (sum == n){
                res.add(new ArrayList<>(oneRes));
            }
            return;
        }

        for (int i = start; i <= 9 - k + level; i++) {
            oneRes.add(i);
            getCombinationSum3(k,n,level + 1,i + 1,res,oneRes);
            oneRes.remove(oneRes.size() - 1);
        }

    }
}
